<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 2017/8/20
 * Time: 下午8:52
 */
class ModAuction
{
    public static function getLink($server='1.1.2.1', $dbName=''){
        $logServer = PubServer::getLogServerByDevId($server);
        if(empty($logServer)){
            return false;
        }

        $config = array(
            'dsn'       =>  'mysql:host='.$logServer.';port=5544',
            'username' =>  'adminlog',
            'password' =>  'romalog@123',
        );
        return new PubDbLink($config, $dbName);
    }

    public static function getOrder($order){
        if(PubFunc::checkEmpty($order, array(0, 1))) return '';
        if(!in_array($order[1], array('asc', 'desc'))){
            $sort = 'asc';
        }else{
            $sort = $order[1];
        }
        return " ORDER BY {$order[0]} {$sort} ";
    }

    public static function indexData($params, $cnt=false){
        $where  = " WHERE dtEventTime BETWEEN :begin AND :end ";
        $args   = array(
            'begin' => $params['time_start'] . ' 00:00:00',
            'end'   => $params['time_end'] . ' 23:59:59'
        );

        if(!empty($params['record_id'])){
            $where .= ' AND RecordItemId=:record_id ';
            $args['record_id'] = $params['record_id'];
        }
        if(!empty($params['sell_id'])){
            $where .= ' AND SellRoleID=:sell_id ';
            $args['sell_id'] = $params['sell_id'];
        }
        if(!empty($params['buy_id'])){
            $where .= ' AND BuyRoleID=:buy_id ';
            $args['buy_id'] = $params['buy_id'];
        }
        if(!empty($params['item_id'])){
            $where .= ' AND ItemID=:item_id ';
            $args['item_id'] = $params['item_id'];
        }

        $dbLink = self::getLink($params['server']);
        if(!$dbLink){
            exit("链接错误，请查看该服务器({$params['server']})的配置是否正确。");
        }

        $dbName = 'romatlogdb';
        $table  = "(";
        for($start=strtotime($params['time_start']), $end=strtotime($params['time_end']), $i=3;
            $start<=$end && $i>0; $start+=86400, $i--){
            $one   = $dbName . '_' . date('Ymd', $start);
            $table .= " (SELECT * FROM {$one}.AuctionTradeRecordFlow {$where}) UNION ALL";
        }
        $table = substr($table, 0, -9);
        $table .= ') AS tbl';

        if($cnt){
            $sql = "select count(1) as cnt from {$table}";
            $result = $dbLink->query($sql, $args);
            return isset($result[0]['cnt']) ? $result[0]['cnt'] : 0;
        }else{
            $order  = self::getOrder($params['order']);
            $limit  = PubFunc::getLimit($params['length'], $params['page']);

            $sql = "SELECT * FROM {$table} {$order} {$limit}";

            return $dbLink->query($sql, $args);
        }
    }

}